//
//  WBNetworkManager.swift
//  仿新浪微博
//
//  Created by 罗超 on 2017/8/16.
//  Copyright © 2017年 LuoChao. All rights reserved.
//

import UIKit
import AFNetworking

//swift 的枚举支持任意数据类型
enum WBHTTPMethod {
    case GET
    case POST
}

///网络管理工具
class WBNetworkManager: AFHTTPSessionManager {

    //静态区、常量、闭包  
    //在第一次访问时，执行闭包，并将结果保存在 shared 常量中
    static let shared = { () -> WBNetworkManager in
        let instance = WBNetworkManager()
        /// 如果解析报错，在这加入对应的反序列化支持类型就可以了
//        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    lazy var userAccount = WBUserAccount()
    
    //用户登录标记 [计算型属性]
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    // 专门负责拼接 token 的网络请求方法
    func tokenRequest(method: WBHTTPMethod = .GET,
                      URLString: String, parameters: [String : Any]?,
                      completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()) {
        
        guard let token = userAccount.access_token else {
            // FIXME: 发送通知，提示用户登录
            print("没有 token! 需要登录")
            completion(nil, false)
            return
        }
        
        //处理 token 字典
        var parameters = parameters as [String: AnyObject]?
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        parameters!["access_token"] = token as AnyObject
        
        //调用 request 发起正真的网络请求
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    /// 封装 get post
    ///
    /// - Parameters:
    ///   - method: GET/POST
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调[json(字典/数组), 是否成功]
    func request(method: WBHTTPMethod = .GET,
                 URLString: String, parameters: [String : Any]?,
                 completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()) {
        
        // 成功回调
        let success = { (task: URLSessionDataTask, json: Any?)->() in
            completion(json, true)
        }
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: Error)->() in
            
            // 针对 403 处理用户 token 过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token 过期了")
                
                // FIXME: 发送通知，提示用户再次登录（本方法不知道被谁调用，谁接收到通知，谁处理！）
            }
            
            print("网络请求错误\(error)")
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
